//
//  FloorView.m
//  OfficeBook
//
//  Created by 孙晓奇 on 15/9/25.
//  Copyright © 2015年 sunny. All rights reserved.
//

#import "FloorView.h"
#import "FloorCollectionViewCell.h"
#import "FloorCollectionViewHeader.h"
#import "BDKCollectionIndexView.h"

#import "RoomModel.h"
#import "FilterModel.h"
#import "LocationModel.h"

NSString * const FloorCellReuseIdentifier   = @"FloorCellReuseIdentifier";
NSString * const FloorHeaderReuseIdentifier = @"FloorHeaderReuseIdentifier";

@interface FloorView()
<UICollectionViewDelegateFlowLayout, UICollectionViewDelegate, UICollectionViewDataSource>

@property (strong, nonatomic) BDKCollectionIndexView     *indexView;
@property (strong, nonatomic) UICollectionView           *collectionView;
@property (nonatomic, strong) UICollectionViewFlowLayout *layout;

//layout and collectionView config
@property (nonatomic, assign) NSInteger numOfItemsInRow;
@property (nonatomic, assign) CGFloat   indexViewWidth;
@property (nonatomic, assign) CGFloat   floorHeaderHeight;
@property (nonatomic) UIEdgeInsets      sectionMargin;

@property (nonatomic, strong) NSMutableArray *roomList;

@end

@implementation FloorView

-(instancetype)initWithFrame:(CGRect)frame{
    // lauout configiure
    self.indexViewWidth   = 28.f;
    self.floorHeaderHeight = 28.f;
    self.numOfItemsInRow = 4;
    self.sectionMargin = UIEdgeInsetsMake(10.f, 10.f, 10.f, self.indexViewWidth);
    
    self.roomList = [[NSMutableArray alloc] init];
    
#warning fixme
    FilterModel *filter = [[FilterModel alloc] init];
    filter.location.id = 2;       //for test
    [self refreshRoomList:filter];  // get data from server
    
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        
        self.layout = [[UICollectionViewFlowLayout alloc] init];
        self.layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        CGFloat itemWidth = (frame.size.width - self.numOfItemsInRow * self.sectionMargin.left - self.indexViewWidth) / 4;    //每行四个item
        self.layout.itemSize = CGSizeMake(itemWidth, itemWidth + 16.f);   //title height 16.f
        self.layout.sectionInset = self.sectionMargin;
        
        // add collectionView
        self.collectionView = [[UICollectionView alloc] initWithFrame:self.bounds collectionViewLayout:self.layout];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.scrollEnabled = YES;
        self.collectionView.showsVerticalScrollIndicator = NO;
        [self addSubview:self.collectionView];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        
        [self.collectionView registerClass:[FloorCollectionViewCell class] forCellWithReuseIdentifier:FloorCellReuseIdentifier];
        [self.collectionView registerClass:[FloorCollectionViewHeader class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:FloorHeaderReuseIdentifier];
        
        // add indexView
        self.indexView = [BDKCollectionIndexView indexViewWithFrame:CGRectZero indexTitles:nil];
        self.indexView.translatesAutoresizingMaskIntoConstraints = NO;          // auto layout
        [self.indexView addTarget:self action:@selector(indexViewValueChanged:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:self.indexView];
        
        [self.indexView makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.top);
            make.bottom.equalTo(self.bottom);
            make.width.equalTo(@(self.indexViewWidth));
            make.right.equalTo(self.right);
        }];
    }
    return self;
}

#pragma mark Flow Layout
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
    return CGSizeZero;
}

-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    return CGSizeMake(self.floorHeaderHeight, self.floorHeaderHeight);
}

#pragma mark Data Source
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return [self.roomList count];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return [self.roomList[section] count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    FloorCollectionViewCell *cell = (FloorCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:FloorCellReuseIdentifier forIndexPath:indexPath];
    NSDictionary *room = self.roomList[indexPath.section][indexPath.item];
    int capacity = [room[@"capacity"] intValue];
    int state = [room[@"state"] intValue];
    cell.imageView.image = [UIImage imageNamed:[self roomImageNameWithCapaciity:capacity state:state]];
    cell.titleLabel.text = room[@"name"];
    
    return cell;
}

-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    if (kind == UICollectionElementKindSectionHeader) {
        FloorCollectionViewHeader *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:FloorHeaderReuseIdentifier forIndexPath:indexPath];
        header.title = [NSString stringWithFormat:@"%iF", [self.roomList[indexPath.section][0][@"floor"] intValue]];
        return header;
    }
    return nil;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary *roomDict = self.roomList[indexPath.section][indexPath.item];
    RoomModel *room = [[RoomModel alloc] initWithDictionary:roomDict];
    [self.delegate floorView:self didSelectedMeetingRoom:room];
}

#pragma mark - Index View Actions
- (void)indexViewValueChanged:(BDKCollectionIndexView *)sender {
    NSIndexPath *path = [NSIndexPath indexPathForItem:0 inSection:sender.currentIndex];
    if (![self collectionView:self.collectionView cellForItemAtIndexPath:path])
        return;
    //[self.collectionView scrollToItemAtIndexPath:path atScrollPosition:UICollectionViewScrollPositionTop animated:NO];
    //CGFloat yOffset = self.collectionView.contentOffset.y - self.floorHeaderHeight - self.sectionMargin.top;
    UICollectionViewLayoutAttributes *attributes = [self.collectionView layoutAttributesForSupplementaryElementOfKind:UICollectionElementKindSectionHeader atIndexPath:path];
    CGFloat yOffset = MAX(MIN(attributes.frame.origin.y, self.collectionView.contentSize.height - self.collectionView.frame.size.height), 0);
    self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x, yOffset);
}

-(NSString *)roomImageNameWithCapaciity:(int) capacity state:(int)state{
    NSString *capStr, *stateStr;
    stateStr = (state == 1? @"Free": (state == 2? @"Used": @"Busy"));
    capStr = (capacity <= 5? @"Small": (capacity <= 10? @"Middle": (capacity <= 15? @"Large": @"VeryLarge")));
    
    return [NSString stringWithFormat:@"room%@%@", stateStr, capStr];
}

-(void)refreshRoomList:(FilterModel *)filter {
    if (filter == nil) {
        return;
    }
    HTTPManager *manager = [HTTPManager manager];
    [manager getOfficeRoomList:filter success:^(NSArray *responseObject) {
        NSArray *rawRoomList = responseObject;
        
        [self.roomList removeAllObjects];
        __block int maxFloor = 1;
        [rawRoomList enumerateObjectsUsingBlock:^(id room, NSUInteger idx, BOOL * _Nonnull stop) {
            maxFloor = MAX(maxFloor, [room[@"floor"] intValue]);
        }];
        for (int f = 1; f <= maxFloor; f++) {
            NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF[%@] == %i", @"floor", f];
            NSArray *fr = [rawRoomList filteredArrayUsingPredicate:pred];
            if ([fr count] > 0) {
                [self.roomList addObject: fr];
            }
        }
        //index view
        NSMutableArray *indexTitles = [[NSMutableArray alloc] init];
        for (int i = 0; i < [self.roomList count]; i ++) {
            [indexTitles addObject:[NSString stringWithFormat:@"%iF", [self.roomList[i][0][@"floor"] intValue]]];
        }
        [self.indexView setIndexTitles:indexTitles];
        
        [self.collectionView reloadData];
        
    } failure:^(NSError *error) {
        // fail to connect
    }];
}

@end
